<?php
class o2o_ctl_admin_inventory extends desktop_controller {

    var $name = "门店盘点";
    var $workground = "o2o_center";
    
    //分类导航
    function _views(){
        $sub_menu = array(
                0 => array('label'=>app::get('base')->_('全部'),'optional'=>false),
                1 => array('label'=>app::get('base')->_('未确认'),'filter'=>array('status'=>1),'optional'=>false),
                2 => array('label'=>app::get('base')->_('已确认'),'filter'=>array('status'=>2),'optional'=>false),
                3 => array('label'=>app::get('base')->_('作废'),'filter'=>array('status'=>3),'optional'=>false),
        );
        $mdlO2oInventory = app::get('o2o')->model("inventory");
        $i=0;
        foreach($sub_menu as $k=>$v){
            if (!IS_NULL($v['filter'])){
                $v['filter'] = $v['filter'];
            }
            $sub_menu[$k]['filter'] = $v['filter']?$v['filter']:null;
            $sub_menu[$k]['addon'] = $mdlO2oInventory->count($v['filter']);
            $sub_menu[$k]['href'] = 'index.php?app=o2o&ctl='.$_GET['ctl'].'&act='.$_GET['act'].'&view='.$i++;
        }
        return $sub_menu;
    }

    function index(){
        $this->title = '盘点列表';
        $this->action = array(
                array('label' =>'模板导出', 'href' => 'index.php?app=o2o&ctl=admin_inventory&act=export', 'target' => 'dialog::{width:700,height:260,title:\'模板导出\'}'),
                array('label' =>'盘点导入', 'href' => 'index.php?app=o2o&ctl=admin_inventory&act=import', 'target' => 'dialog::{width:400,height:110,title:\'盘点导入\'}'),
                array('label'=>app::get('desktop')->_('作废'),'icon'=>'add.gif','confirm'=>app::get('desktop')->_('确定作废选中项？作废后将不可恢复'),'submit'=>'index.php?app=o2o&ctl=admin_inventory&act=doCancel'),
                array('label'=>app::get('desktop')->_('删除'),'icon'=>'add.gif','confirm'=>app::get('desktop')->_('确定删除选中项？删除后将不可恢复'),'submit'=>'index.php?app=o2o&ctl=admin_inventory&act=batch_delete'),
        );
        
        $base_filter = array();
        
        //过滤选择门店的下拉框 类别头部筛选
        $post_selected_store_bn = trim($_POST['selected_store_bn']);
        if($post_selected_store_bn && $post_selected_store_bn!="_NULL_"){
            //获取branch_id
            $mdlOmeBranch = app::get('ome')->model('branch');
            $rs_branch_id = $mdlOmeBranch->dump(array("branch_bn"=>$post_selected_store_bn),"branch_id");
            $base_filter['branch_id'] = $rs_branch_id['branch_id'];
        }
        
        $params = array(
                'title'=>$this->title,
                'use_buildin_recycle'=>false,
                'base_filter'=>$base_filter,
                'orderBy'=>'inventory_id DESC',
                'actions'=>$this->action,
        );
        
        //在列表上方添加过滤门店
        if(!isset($_GET['action'])) {
            $panel = new desktop_panel($this);
            $panel->setId('inventory_finder_top');
            $panel->setTmpl('admin/finder/inventory_finder_panel_filter.html');
            $panel->show('o2o_mdl_inventory', $params);
        }
    
        $this->finder('o2o_mdl_inventory', $params);
    }
    
    //导出加载页
    function export(){
        $this->page("admin/inventory/export.html");
    }
    
    //导入加载页
    function import(){
        $this->page('admin/inventory/import.html');
    }
    
    //批量的和单个的作废
    function doCancel(){
        $this->begin();
        $inventory_ids = array();
        if(isset($_GET["inventory_id"])){
            //单个的作废
            $inventory_ids[] = $_GET["inventory_id"];
        }else{
            if(isset($_POST['inventory_id'])){
                //批量的作废
                $inventory_ids = $_POST['inventory_id'];
            }
        }
        if(empty($inventory_ids)){
            $this->end(false, '没有选中的盘点记录');
        }
    
        $mdlO2oInventory = app::get('o2o')->model('inventory');
        $rs_inventory = $mdlO2oInventory->dump(array("status|in"=>array(2,3),"inventory_id|in"=>$inventory_ids),"inventory_id");
        if(!empty($rs_inventory)){
            $this->end(false, '请确认盘点单必须是未确认的状态');
        }
        $result = kernel::single('o2o_inventorylist')->cancel_inventory($inventory_ids);
        if($result){
            $this->end(true, '操作成功','javascript:finderGroup["'.$_GET['finder_id'].'"].refresh();');
        }
    }
    
    //批量删除
    function batch_delete(){
        $this->begin();
        $inventory_ids = $_POST['inventory_id'];
        if(empty($inventory_ids)){
            $this->end(false, '请选择记录');
        }
        $mdlO2oInventory = app::get('o2o')->model('inventory');
        $rs_inventory = $mdlO2oInventory->dump(array("status"=>2,'inventory_id|in'=>$inventory_ids),'inventory_id');
        if(!empty($rs_inventory)){
            $this->end(false, '不能删除已确认的盘点单');
        }
        $result = kernel::single('o2o_inventorylist')->delete_inventory($inventory_ids);
        if($result){
            $this->end(true, '操作成功','javascript:finderGroup["'.$_GET['finder_id'].'"].refresh();');
        }
    }
    
    //查看明细
    function detail_inventory($inventory_id=null, $page=1){
        $inventory_id = intval($inventory_id);
        $page = intval($page);
        $page = $page ? $page : 1;
        $pagelimit = 10;
        $this->pagedata["inv_info"] = kernel::single('o2o_inventorylist')->get_basic_info($inventory_id);
        $this->pagedata["items"] = kernel::single('o2o_inventorylist')->get_inventory_item_list(array("inventory_id"=>$inventory_id),$pagelimit*($page-1),$pagelimit,"item_id asc");
        $this->pagedata["count"] = kernel::single('o2o_inventorylist')->get_inventory_count(array("inventory_id"=>$inventory_id));
        $this->pagedata["pagelimit"] = $pagelimit;
        $this->pagedata["pager"] = $this->ui()->pager(array(
                'current'=>$page,
                'total'=>ceil($this->pagedata["count"]/$pagelimit),
                'link'=>'index.php?app=o2o&ctl=admin_inventory&act=detail_inventory&p[0]='.$inventory_id.'&p[1]=%d',
        ));
        $this->page("admin/inventory/detail_inventory.html");
    }
    
    //编辑页
    function edit_inventory(){
        $inventory_id = intval($_GET['inventory_id']);
        $this->pagedata["inv_info"] = kernel::single('o2o_inventorylist')->get_basic_info($inventory_id);
        $this->singlepage('admin/inventory/edit_inventory.html');
    }
    
    //获取盘点明细
    function getItems(){
        $inventory_id = $_GET["inventory_id"];
        $branch_id = $_GET["branch_id"];
        //基础物料编码
        if($_GET['bn']){
            $filter = array(
                    'material_bn'=>$_GET['bn']
            );
        }
        //基础物料名称
        if($_GET['name']){
            $filter = array(
                    'material_name'=>$_GET['name']
            );
        }
        if(!$filter){
            return false;
        }
        //是否存在此基础物料
        $mdlMaterialBasicMaterial = app::get('material')->model('basic_material');
        $rs_material = $mdlMaterialBasicMaterial->dump($filter,"bm_id,material_name,material_bn");
        if(empty($rs_material)){
            return false;
        }
        //是否此基础物料存在关联关系
        $mdlO2oBranchProduct = app::get('o2o')->model('branch_product');
        $rs_branch_product = $mdlO2oBranchProduct->dump(array("branch_id"=>$branch_id,"bm_id"=>$rs_material["bm_id"]),"id");
        if(empty($rs_branch_product)){
            return false;
        }
        //获取基础物料规格
        $mdlMaterialBasicMaterialExt = app::get('material')->model('basic_material_ext');
        $rs_basic_ext = $mdlMaterialBasicMaterialExt->dump(array("bm_id"=>$rs_material["bm_id"]),"specifications");
        //组织数据
        $mdlO2oInventoryItems = app::get('o2o')->model('inventory_items');
        $rs_items = $mdlO2oInventoryItems->dump(array("inventory_id"=>$inventory_id,"bm_id"=>$rs_material["bm_id"]),"*");
        $rs_items["product_id"] = $rs_material["bm_id"];
        $rs_items["bn"] = $rs_material["material_bn"];
        $rs_items["name"] = $rs_material["material_name"];
        $rs_items["spec_info"] = "-";
        if($rs_basic_ext["specifications"]){
            $rs_items["spec_info"] = $rs_basic_ext["specifications"];
        }
        if(isset($rs_items["accounts_num"])){
            //有明细表数据 直接取明细表中的数值
        }else{
            //有关联物料 导入生成明细时 没有此物料的item明细数据 点击保存可新加进明细数据
            $rs_items["accounts_num"] = 0;
            $rs_items["accounts_share_num"] = 0;
            $rs_items["actual_num"] = 0;
            $rs_items["actual_share_num"] = 0;
            //如有库存实际数记录则取
            $mdlO2oProductStore = app::get('o2o')->model('product_store');
            $rs_product_store = $mdlO2oProductStore->dump(array("branch_id"=>$branch_id,"bm_id"=>$rs_material["bm_id"]),"store,share_store");
            if(!empty($rs_product_store)){
                $rs_items["actual_num"] = $rs_product_store["store"];
                $rs_items["actual_share_num"] = $rs_product_store["share_store"];
            }
            $rs_items["short_over"] = 0;
            $rs_items["share_short_over"] = 0;
        }
        $rows[] = $rs_items;
        echo "window.autocompleter_json=".json_encode($rows);
    }
    
    //编辑页 保存
    function doEdit(){
        $this->begin();
        $inventory_id = $_POST['inventory_id'];
        $branch_id = $_POST['branch_id'];
        $an = $_POST['an'];
        $as = $_POST['as'];
        if(!$an || !$as){
            $this->end(false, '盘点明细不能为空');
        }
        $incorrect_input = false;
        $bm_ids = array();
        $rl_bm_id_value = array();
        foreach ($an as $k => $a){
            $bm_ids[] = $k;
            $a = trim($a);
            if(!is_numeric($a) || $a < 0){
                $incorrect_input = true;
            }
            $rl_bm_id_value[$k]["accounts_num"] = $a;
        }
        foreach ($as as $k_s => $a_s){
            $a_s = trim($a_s);
            if(!is_numeric($a_s) || $a_s < 0){
                $incorrect_input = true;
            }
            $rl_bm_id_value[$k_s]["accounts_share_num"] = $a_s;
        }
        if($incorrect_input){
            $this->end(false, '请正确填写数量');
        }
        //有盘点明细有库存记录的 更新盘点明细和库存记录 没有的话新增
        $mdlO2oProductStore = app::get('o2o')->model('product_store');
        $mdlO2oInventoryItems = app::get('o2o')->model('inventory_items');
        //是否有库存记录 没有的话后续新增
        $have_not_p_s_bm_ids = array();
        $have_p_s_bm_ids = array();
        $rs_product_store = $mdlO2oProductStore->getList("bm_id,store,share_store",array("branch_id"=>$branch_id,"bm_id|in"=>$bm_ids));
        $rl_bm_id_store = array();
        if(empty($rs_product_store)){
            $have_not_p_s_bm_ids[] = $bm_ids;
        }else{
            foreach ($rs_product_store as $var_p_s){
                $have_p_s_bm_ids[] = $var_p_s["bm_id"];
                $rl_bm_id_store[$var_p_s["bm_id"]] = array(
                    "store" => $var_p_s["store"],
                    "share_store" => $var_p_s["share_store"],
                );
            }
            foreach ($bm_ids as $var_bm_id){
                if(!in_array($var_bm_id,$have_p_s_bm_ids)){
                    $have_not_p_s_bm_ids[] = $var_bm_id;
                }
            }
        }
        //是否有盘点明细
        $have_not_i_i_bm_ids = array();
        $have_i_i_bm_ids = array();
        $rs_inventory_items = $mdlO2oInventoryItems->getList("bm_id",array("inventory_id"=>$inventory_id,"bm_id|in"=>$bm_ids));
        if(empty($rs_inventory_items)){
            $have_not_i_i_bm_ids[] = $bm_ids;
        }else{
            foreach ($rs_inventory_items as $var_i_i){
                $have_i_i_bm_ids[] = $var_i_i["bm_id"];
            }
            foreach ($bm_ids as $v_bm_id){
                if(!in_array($v_bm_id,$have_i_i_bm_ids)){
                    $have_not_i_i_bm_ids[] = $v_bm_id;
                }
            }
        }
        //开始更新 新建记录
        if (!empty($have_not_p_s_bm_ids)){
            //新建库存记录
            foreach ($have_not_p_s_bm_ids as $var_p){
                $insert_p_s_arr = array(
                    "branch_id" => $branch_id,
                    "bm_id" => $var_p,
                );
                $mdlO2oProductStore->insert($insert_p_s_arr);
            }
        }
        if(!empty($have_not_i_i_bm_ids)){
            //新建盘点明细记录
            foreach ($have_not_i_i_bm_ids as $var_i){
                $accounts_num = intval($rl_bm_id_value[$var_i]["accounts_num"]);
                $accounts_share_num = intval($rl_bm_id_value[$var_i]["accounts_share_num"]);
                $actual_num = 0;
                $actual_share_num = 0;
                if(isset($rl_bm_id_store[$var_i]["store"])){
                    $actual_num = intval($rl_bm_id_store[$var_i]["store"]);
                }
                if(isset($rl_bm_id_store[$var_i]["share_store"])){
                    $actual_share_num = intval($rl_bm_id_store[$var_i]["share_store"]);
                }
                $short_over = $accounts_num - $actual_num;
                $share_short_over = $accounts_share_num - $actual_share_num;
                $insert_i_i_arr = array(
                    "inventory_id" => $inventory_id,
                    "bm_id" => $var_i,
                    "accounts_num" => $accounts_num,
                    "accounts_share_num" => $accounts_share_num,
                    "actual_num" => $actual_num,
                    "actual_share_num" => $actual_share_num,
                    "short_over" => $short_over,
                    "share_short_over" => $share_short_over,
                );
                $mdlO2oInventoryItems->insert($insert_i_i_arr);
            }
        }
        if(!empty($have_i_i_bm_ids)){
            //更新盘点明细记录
            foreach ($have_i_i_bm_ids as $var_h_i){
                $accounts_num = intval($rl_bm_id_value[$var_h_i]["accounts_num"]);
                $accounts_share_num = intval($rl_bm_id_value[$var_h_i]["accounts_share_num"]);
                $actual_num = intval($rl_bm_id_store[$var_h_i]["store"]);
                $actual_share_num = intval($rl_bm_id_store[$var_h_i]["share_store"]);
                $short_over = $accounts_num - $actual_num;
                $share_short_over = $accounts_share_num - $actual_share_num;
                $update_arr = array(
                    "accounts_num"=>$accounts_num,
                    "accounts_share_num"=>$accounts_share_num,
                    "actual_num"=>$actual_num,
                    "actual_share_num"=>$actual_share_num,
                    "short_over"=>$short_over,
                    "share_short_over"=>$share_short_over,
                );
                $filter_arr = array("inventory_id"=>$inventory_id,"bm_id"=>$var_h_i);
                $mdlO2oInventoryItems->update($update_arr,$filter_arr);
            }
        }
        
        //记录日志
        $opObj = app::get('ome')->model('operation_log');
        $opObj->write_log('inventory_edit@o2o', $inventory_id, '门店盘点单编辑成功');
        
        $this->end(true, '已完成');
    }
    
    //确认页
    function confirm_inventory($inventory_id=null, $page=1){
        $inventory_id = intval($inventory_id);
        $page = intval($page);
        $page = $page ? $page : 1;
        $pagelimit = 10;
        $this->pagedata["inventory_id"] = $inventory_id;
        $this->pagedata["inv_info"] = kernel::single('o2o_inventorylist')->get_basic_info($inventory_id);
        $this->pagedata["branch_id"] = $this->pagedata["inv_info"]["branch_id"];
        $this->pagedata["items"] = kernel::single('o2o_inventorylist')->get_inventory_item_list(array("inventory_id"=>$inventory_id),$pagelimit*($page-1),$pagelimit,"item_id asc");
        $this->pagedata["count"] = kernel::single('o2o_inventorylist')->get_inventory_count(array("inventory_id"=>$inventory_id));
        $this->pagedata["pagelimit"] = $pagelimit;
        $this->pagedata["pager"] = $this->ui()->pager(array(
                'current'=>$page,
                'total'=>ceil($this->pagedata["count"]/$pagelimit),
                'link'=>'index.php?app=o2o&ctl=admin_inventory&act=confirm_inventory&p[0]='.$inventory_id.'&p[1]=%d',
        ));
        $this->page("admin/inventory/confirm_inventory.html");
    }
    
    //确认页 确认
    function doConfirm(){
        $this->begin();
        
        if(!$_POST["inventory_id"] || !$_POST["branch_id"]){
            $this->end(false,'无效操作');
        }
        
        $mdlO2oInventory = app::get('o2o')->model('inventory');
        $mdlO2oInventoryItems = app::get('o2o')->model('inventory_items');
        $mdlO2oProductStore = app::get('o2o')->model('product_store');
        
        //获取主盘点单的数据
        $rs_inventory = $mdlO2oInventory->dump(array("inventory_id"=>$_POST["inventory_id"]));
        
        //获取盘点明细的盘盈亏数据
        $rs_inventory_items = $mdlO2oInventoryItems->getList("bm_id,short_over,share_short_over",array("inventory_id"=>$_POST["inventory_id"]));
        $rl_bm_id_short = array();
        foreach ($rs_inventory_items as $var_i_i){
            $rl_bm_id_short[$var_i_i["bm_id"]] = array(
                    "short_over" => $var_i_i["short_over"],
                    "share_short_over" => $var_i_i["share_short_over"],
            );
        }
        //获取库存数据
        $rs_store = $mdlO2oProductStore->getList("id,bm_id,store,share_store",array("branch_id"=>$_POST["branch_id"]));
        $rs_product_store = array();
        //统一获取打库存更新数组
        foreach($rs_store as $var_f){
            $update_store = $var_f["store"] + $rl_bm_id_short[$var_f["bm_id"]]["short_over"];
            $update_share_store = $var_f["share_store"] + $rl_bm_id_short[$var_f["bm_id"]]["share_short_over"];
            if($update_store < 0){
                $update_store = 0;
            }
            if($update_share_store < 0){
                $update_share_store = 0;
            }
            $rs_product_store[] = array(
                    "id" => $var_f["id"],
                    "bm_id" => $var_f["bm_id"],
                    "store" => $update_store,
                    "share_store" => $update_share_store,
                    "short_over" => intval($rl_bm_id_short[$var_f["bm_id"]]["short_over"]),
                    "share_short_over" => intval($rl_bm_id_short[$var_f["bm_id"]]["share_short_over"]),
            );
        }
        
        //入队列
        $oQueue = app::get('base')->model('queue');
        //每10个基础物料 一个队列
        $number = $page = 0;   $limit = 10;
        
        $psdf = array(
            "rs_inventory" => $rs_inventory,
            "branch_id" => $_POST["branch_id"],
            "confirm_op_id" => kernel::single('desktop_user')->get_id(),
        );
        
        $sdfs = array();
        foreach ($rs_product_store as $k => $v){
            if ($number < $limit){
                $number++;
            }else{
                $page++;
                $number = 0;
            }
            $sdfs[$page][] = $v;
        }
        
        foreach ($sdfs as $i){
            $psdf['products'] = $i;
            $queueData = array(
                    'queue_title'=>'门店盘点确认',
                    'start_time'=>time(),
                    'params'=>array(
                        'sdfdata'=>$psdf,
                        'app' => 'o2o',
                        'mdl' => 'inventory'
                    ),
                    'worker'=>'o2o_inventory_confirm.run',
            );
            $oQueue->save($queueData);
        }
        
        //记录日志
        $opObj = app::get('ome')->model('operation_log');
        $opObj->write_log('inventory_confirm@o2o', $rs_inventory["inventory_id"], '门店盘点单确认成功');
        
        $this->end(true,'操作成功');
    }
    
    //branch_id判是否有存在o2o库存
    function hasO2oStore(){
        $branch_bn = $_POST["branch_bn"];
        $mdlOmeBranch = app::get('ome')->model('branch');
        $mdlO2oProductStore = app::get('o2o')->model('product_store');
        //获取branch_id
        $rs_branch = $mdlOmeBranch->dump(array("branch_bn"=>$branch_bn,"b_type"=>2),"branch_id");
        $rs_store = $mdlO2oProductStore->dump(array("branch_id"=>$rs_branch["branch_id"]));
        if(empty($rs_store)){
            echo false;
        }else{
            echo true;
        }
    }
    
}